package com.itboye.sunsun.shop.ui;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.itboye.sunsun.R;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.support.BaseDialogFragment;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.open.yyb.AppbarAgent;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

@SuppressLint("NewApi")
public class ShareFragment extends BaseDialogFragment implements
		OnClickListener {

	private static final String APP_ID = "wxa30658c4f4f6bbf4";
	private IWXAPI api;
	private String id;
	private String type;
	private String goodsName;
	private String AppUrl = NetPublicConstant.secondUrl+"/Webview";
	private String imgUrl;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 取消标题栏

		// setStyle(DialogFragment.STYLE_NO_FRAME,R.style.shareDialog);

		// 设置底部显示

		// 设置监听事件
		View view = inflater.inflate(R.layout.share_fragment, container);
		RelativeLayout sinaRela = (RelativeLayout) view
				.findViewById(R.id.sinarela);
		sinaRela.setOnClickListener(this);
		RelativeLayout wxRela = (RelativeLayout) view.findViewById(R.id.werela);
		wxRela.setOnClickListener(this);
		RelativeLayout wecircleRela = (RelativeLayout) view
				.findViewById(R.id.wecirclerela);
		wecircleRela.setOnClickListener(this);
		api = WXAPIFactory.createWXAPI(App.ctx, APP_ID);

		Bundle bundle = getArguments();
		try {
			id = bundle.getString("id");
			type = bundle.getString("type");
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			goodsName = bundle.getString("goodsName");
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			imgUrl = bundle.getString("imgUrl");
		} catch (Exception e) {
			// TODO: handle exception
		}

		return view;
	}

	private final String APPID = "1105251111";
	private Runnable runnable2=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			//请求网址
			WXWebpageObject webpage=new WXWebpageObject();
			
			//传入的网址
			webpage.webpageUrl=NetPublicConstant.secondUrl+"/Webview/User/download?type=product&id="
					+ id + "&from=groupmessage&isappinstalled=0";
			Bitmap thumb=null;
			
			//标题
			WXMediaMessage msg=new WXMediaMessage(webpage);
			msg.title=goodsName;
			thumb=Bitmap.createScaledBitmap(GetLocalOrNetBitmap(imgUrl), 120, 120, true);//压缩Bitmap
			thumb=compressImage(thumb);
			//商品图片
		
			msg.setThumbImage(thumb);
			System.out.println(thumb.getHeight()+"高");//, 0).show();
//			//构建一个请求
			SendMessageToWX.Req req=new SendMessageToWX.Req();
			req.message=msg;
			req.scene=SendMessageToWX.Req.WXSceneTimeline;
			req.transaction=
			req.transaction="webpage";
			api.sendReq(req);
		}
	};

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mTencent = Tencent.createInstance(APPID, getActivity());
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
//		UMImage image = new UMImage(App.ctx,
//				"http://www.umeng.com/images/pic/social/integrated_3.png");
		switch (id) {
		case R.id.sinarela:
			 /** shareaction need setplatform , callbacklistener,and content(text,image).then share it **/
//            new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
//                    .withText("hello umeng video")
//                    .withMedia(image)
//                    .share();
			shareToQQ();
            break;
		case R.id.werela:
			
			new Thread(runnable).start();
			
			
			break;
		case R.id.wecirclerela:
			
			new Thread(runnable2).start();
			
			break;

		default:
			break;
		}
	}

	Runnable runnable=new Runnable() {
		
		@Override
		public void run() {
			Bitmap thumb0=null;
			WXWebpageObject webpage0=new WXWebpageObject();//"http://sunsun.itboye.com/index.php/Webview/User/download?type=product&id="+ id + "&from=groupmessage&isappinstalled=0"
			webpage0.webpageUrl=NetPublicConstant.secondUrl+"/Webview/User/download?type=product&id="
					+ id + "&from=groupmessage&isappinstalled=0";
			//标题"http://sunsun.itboye.com/index.php/Webview/User/download?type=product&id="+ id + "&from=groupmessage&isappinstalled=0"
			WXMediaMessage msg0=new WXMediaMessage(webpage0);
			msg0.title=goodsName;
			msg0.description=NetPublicConstant.secondUrl+"/Webview/User/download?type=product&id="+id+"&from=groupmessage&isappinstalled=0";
			thumb0=Bitmap.createScaledBitmap(GetLocalOrNetBitmap(imgUrl), 120, 120, true);//压缩Bitmap
			thumb0=compressImage(thumb0);
			System.out.println(thumb0.getHeight()+"高2");
//		} catch (Exception e) {
//			
//			thumb0=BitmapFactory.decodeResource(getResources(),R.drawable.ic_logo);
//		}
		msg0.setThumbImage(thumb0);
		//构建一个请求
		SendMessageToWX.Req req0=new SendMessageToWX.Req();
		req0.message=msg0;
		req0.scene=SendMessageToWX.Req.WXSceneSession;
		req0.transaction="sessionwebpage";
		api.sendReq(req0);
		}
	};
	Tencent mTencent;

	private void shareToQQ() {
		System.out.println("imgURl"+imgUrl);
		final Bundle params = new Bundle();
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
				QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_TITLE, goodsName);
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY,
				NetPublicConstant.secondUrl+"/Webview/User/download?type=product&id="
						+ id + "&from=groupmessage&isappinstalled=0");
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,
				NetPublicConstant.secondUrl+"/Webview/User/download?type=product&id="
						+ id + "&from=groupmessage&isappinstalled=0");
		params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "森森休闲");
		// params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
		mTencent.shareToQQ(getActivity(), params, new IUiListener() {

			@Override
			public void onError(UiError arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "分享失败", 0).show();
			}

			@Override
			public void onComplete(Object arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "分享完成", 0).show();
			}

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "已取消", 0).show();
			}
		});

	}

	// private UMShareListener umShareListener = new UMShareListener() {
	// @Override
	// public void onResult(SHARE_MEDIA platform) {
	// // Toast.makeText(ShareActivity.this, platform + " 分享成功啦",
	// // Toast.LENGTH_SHORT).show();
	// }
	//
	// @Override
	// public void onError(SHARE_MEDIA platform, Throwable t) {
	// // Toast.makeText(ShareActivity.this,platform + " 分享失败啦",
	// // Toast.LENGTH_SHORT).show();
	// }
	//
	// @Override
	// public void onCancel(SHARE_MEDIA platform) {
	// // Toast.makeText(ShareActivity.this,platform + " 分享取消了",
	// // Toast.LENGTH_SHORT).show();
	// }
	// };

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
//		UMShareAPI.get(App.ctx).onActivityResult(requestCode, resultCode, data);
	}

	private Bitmap getBitmap(String imgUrl) {
		URL myFileUrl = null; 

		Bitmap bitmap = null; 
		try { 
		myFileUrl = new URL(imgUrl); 
		} catch 
		(MalformedURLException e) { 
		e.printStackTrace(); 
		} 
		try { 

		HttpURLConnection conn = (HttpURLConnection) myFileUrl 

		.openConnection(); 
		conn.setDoInput(true); 
		conn.connect(); 

		InputStream is = conn.getInputStream(); 
		bitmap = 
		BitmapFactory.decodeStream(is); 
		is.close(); 
		} catch (IOException e) { 

		e.printStackTrace(); 
		} 
		return createBitmapThumbnail(bitmap); 
	}

	public Bitmap createBitmapThumbnail(Bitmap bitMap) {  
	    int width = bitMap.getWidth();  
	    int height = bitMap.getHeight();  
	    // 设置想要的大小  
	    int newWidth = 99;  
	    int newHeight = 99;  
	    // 计算缩放比例  
	    float scaleWidth = ((float) newWidth) / width;  
	    float scaleHeight = ((float) newHeight) / height;  
	    // 取得想要缩放的matrix参数  
	    Matrix matrix = new Matrix();  
	    matrix.postScale(scaleWidth, scaleHeight);  
	    // 得到新的图片  
	    Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,  
	            matrix, true);  
	    return newBitMap;  
	}  
	
	private Bitmap compressImage(Bitmap image) {  
		  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        image.compress(Bitmap.CompressFormat.JPEG, 90, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中  
        int options = 100;  
        while ( baos.toByteArray().length / 1024>63) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
            baos.reset();//重置baos即清空baos  
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
        return bitmap;  
    }  
	
	/**
	 * 把网络资源图片转化成bitmap
	 * @param url  网络资源图片
	 * @return  Bitmap
	 */
	public static Bitmap GetLocalOrNetBitmap(String url) {
	    Bitmap bitmap = null;
	    InputStream in = null;
	    BufferedOutputStream out = null;
	    try {
	        in = new BufferedInputStream(new URL(url).openStream(), 1024);
	        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
	        out = new BufferedOutputStream(dataStream, 1024);
	        copy(in, out);
	        out.flush();
	        byte[] data = dataStream.toByteArray();
	        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
	        data = null;
	        return bitmap;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return null;
	    }
	}
	private static void copy(InputStream in, OutputStream out)
	        throws IOException {
	    byte[] b = new byte[1024];
	    int read;
	    while ((read = in.read(b)) != -1) {
	        out.write(b, 0, read);
	    }
	}
}
